package com.juma.vms.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 功能 :
 *
 * @author : Bruce(刘正航) 7:10 PM 2018/12/8
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ValidUtils {
    /**需要校验的对象**/
    public static <T> boolean valid(T obj,Class<?>...groups) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> violations = validator.validate(obj,groups);
        if (violations != null && !violations.isEmpty()) {
            throw new RuntimeException(violations.iterator().next().getMessage());
        }
        return true;
    }
}
